package com.azunitech.jms.ejb;

import java.util.Arrays;

import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.ejb.MessageDriven;
import javax.ejb.MessageDrivenContext;
import javax.jms.BytesMessage;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.StreamMessage;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.apache.log4j.Logger;

import com.azunitech.jms.common.domains.PartsEntity;
/**
 * Message-Driven Bean implementation class for: MyMessageBean
 */
@MessageDriven(mappedName="Queue-1")
public class MyMessageBean implements MessageListener {
	private Logger s_Logger = Logger.getLogger(MyMessageBean.class);
	@Resource
    private MessageDrivenContext mdc;
	
	Context jndiContext;

	@EJB HelloService hello;
	
    public MyMessageBean()  {
    }
 	
    public void onMessage(Message inMessage) {
		try {
			s_Logger.info(inMessage.getJMSDestination());
		} catch (JMSException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
    	
        TextMessage msg = null;
         try {
            if (inMessage instanceof TextMessage) {
                msg = (TextMessage) inMessage;
                String str = msg.getText();
                s_Logger.info("MESSAGE BEAN: Message received: " + msg.getText());
                String echo = hello.greet(msg.getText());
                s_Logger.info("MESSAGE BEAN: Call Hello Service: " + echo);
				deliverTicket(msg);
             }
    		else if (inMessage instanceof ObjectMessage){
    			ObjectMessage objMsg = (ObjectMessage)inMessage;
    			Object msgObject = objMsg.getObject();
				if ( msgObject instanceof PartsEntity){
					s_Logger.info(msgObject.toString());
				}
				s_Logger.info(msgObject.toString());
    		}
       		else if (inMessage instanceof MapMessage){
       			MapMessage mapMessage = (MapMessage)inMessage;
				s_Logger.info(mapMessage.getString("Message type") + " " 
						+ mapMessage.getDouble("A Double") + " " 
						+ mapMessage.getInt("An Integer"));
				
      		}
       		else if ( inMessage instanceof StreamMessage){
       			StreamMessage streamMessage = (StreamMessage)inMessage;
				s_Logger.info(streamMessage.readString() + " " 
						+ streamMessage.readDouble() + " " 
						+ streamMessage.readInt());     			
       		}
       		else if (inMessage instanceof BytesMessage){
       			BytesMessage bytesMessage = (BytesMessage)inMessage;
       			byte[] inByteData = new byte[7];
       			int length = bytesMessage.readBytes(inByteData);
				s_Logger.info(Arrays.toString(inByteData));       			
       		}
            else {
            	String str = inMessage.getClass().getName();
            	s_Logger.warn("Message of wrong type: " + inMessage.getClass().getName());
            }
        } 
        catch (JMSException e) {
            e.printStackTrace();
            mdc.setRollbackOnly();
        } 
        catch (Throwable te) {
            te.printStackTrace();
        }
    }
    
    private QueueConnection conn;
    private QueueSession session;
    public void deliverTicket(TextMessage msg) throws NamingException, JMSException{
    	InitialContext iniCtx = new InitialContext();
        Object tmp = iniCtx.lookup("CF-COMMAND");
        QueueConnectionFactory qcf = (QueueConnectionFactory) tmp;
        conn = qcf.createQueueConnection();
        session = conn.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);
        conn.start();
        
        s_Logger.info("MyMessageBean.onMessage, this=" + hashCode());
        try {
            TextMessage tm = (TextMessage) msg;
            String text = tm.getText() + "processed by: "+hashCode();
            
            Queue queue = (Queue)iniCtx.lookup("Queue-2");
            QueueSender qsender = session.createSender(queue);
    		TextMessage textMessage = session.createTextMessage();
    		textMessage.setText(msg.getText());
			qsender.send(textMessage);
  
        } catch(Throwable t) {
            t.printStackTrace();
        }
 	}
}
